<template>
  <div class="app-container">
    <div style="margin: 4px 0px 20px 4px;">
      <span style="font-size: 20px; font-weight: bold">公共信息</span>
    </div>
    <el-card style="margin-bottom:24px;">
      <el-form ref="public-form" label-position="left">
        <el-form-item label="模板名称">
          <el-input v-model="name" style="width:256px;" size="small" placeholder="请输入模板名称"/>
        </el-form-item>
        <el-form-item style="margin-bottom:4px;" label="备注信息">
          <el-input v-model="description" style="width:256px;" type="textarea" placeholder="请输入备注" :rows="2"
                    size="small"/>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="margin: 4px 0px 20px 4px; width: 100%;">
      <span style="font-size: 20px; font-weight: bold;">表单头模板</span>
      <el-select style="margin-left: 8px;width: 40%" v-model="chooseHeader" value-key="oid" placeholder="请选择" >
        <el-option
          v-for="item in headerTemplates"
          :key="item.oid"
          :label="item.name"
          :value="item">
        </el-option>
      </el-select>
    </div>
    <el-card class="box-card">
      <div v-if="chooseHeader !== null">
        <div v-if="chooseHeader.json==null">
          <tenkvHeader ref="Header" :header-form-origin="headerFormOrigin"/>
        </div>
        <div v-else-if="chooseHeader.hasOwnProperty('json')">
          <v-form-render ref="Header" :form-data="headerFormOrigin" :form-json="chooseHeader.json|cleanJson"/>
        </div>
      </div>
    </el-card>
    <div style="margin: 24px 0px 20px 4px;">
      <span style="font-size: 20px; font-weight: bold">选中的表单项</span>
    </div>
    <el-row :gutter="6" type="flex">
      <el-col :span="19">
        <div v-if="editTemplatesStatus.chosenTemplates.length===0">
          <el-card style="text-align: center;color: #666;font-size:18px;height:600px;">
            请添加表项
          </el-card>
        </div>
        <div v-else>
          <el-card>
            <transition-group name="list-complete" tag="p">
              <div v-for="(item) in editTemplatesStatus.chosenTemplates" :key="item.oid" class="list-complete-item"
                   :style="`background:#FFF;margin-bottom: 24px;z-index:${item.index};`">
                <div v-if="item !== null && item.json==null">
                  <custom-question-block :question-block="item" :order="true"/>
                </div>
                <div v-else-if="item !== null && item.hasOwnProperty('json')">
                  <div style="text-align: right;margin-bottom: 16px;">
                    <el-button-group>
                      <el-button size="small" icon="el-icon-caret-top"
                                 @click="$store.dispatch('app/changeChosenTemplate', {oid:item.oid,type:1})"/>
                      <el-button size="small" icon="el-icon-caret-bottom"
                                 @click="$store.dispatch('app/changeChosenTemplate', {oid:item.oid,type:2})"/>
                      <el-button size="small" icon="el-icon-delete"
                                 @click="$store.dispatch('app/changeChosenTemplate', {oid:item.oid,type:3})"/>
                    </el-button-group>
                  </div>
                  <div>
                    <v-form-render :form-json="getClearFormJson(item.json)">
                    </v-form-render>
                  </div>
                </div>
              </div>
            </transition-group>
          </el-card>
        </div>
      </el-col>
      <el-col :span="5" style="height:100%;">
        <suspend-side-bar/>
      </el-col>
    </el-row>
    <el-row id="editTemplateTail">
      <div style="margin: 20px 0px 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">表尾信息</span>
        <el-select style="margin-left: 8px;width: 40%" v-model="chooseTail" value-key="oid" placeholder="请选择" >
          <el-option
            v-for="item in tailTemplates"
            :key="item.oid"
            :label="item.name"
            :value="item">
          </el-option>
        </el-select>
      </div>
    </el-row>
    <el-card>
      <div v-if="chooseTail !== null">
        <div v-if="chooseTail.json==null">
          <tenkvTail ref="Tail" :tail-form="tailForm"/>
        </div>
        <div v-else-if="chooseTail.hasOwnProperty('json')">
          <v-form-render ref="Tail" :form-data="tailForm" :form-json="getClearFormJson(chooseTail.json)"/>
        </div>
      </div>
    </el-card>
    <el-row style="margin: 24px 0;" type="flex" justify="center">
      <el-col :span="12" style="text-align: center;">
        <el-button v-if="$route.query.mode==='1'" type="primary" @click="submit">新建</el-button>
        <el-button v-else type="primary" @click="submit">保存修改</el-button>
        <el-button @click="$router.push('/staffingSys/orderTemplate')">取消</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import CustomRadio from '@/components/CustomRadio'
import hardCode from '@/utils/templates'
import suspendSideBar from '@/views/editTemplate/suspendSideBar'
import CustomQuestionBlock from '@/components/CustomQuestionBlock'
import {addTemplate, getTemplateBody, getTemplateHeader, getTemplateTail, modifyTemplate} from '@/api/table'
import {handleHeader, headerFormOrigin, sptail} from '@/utils/fix/pre'
import {getClearFormJson} from "@/utils/common";
import tenkvHeader from "@/components/fixedForm/tenkvHeader.vue";
import tenkvTail from "@/components/fixedForm/tenkvTail.vue";

const allComponents = require.context('@/components/CustomQuestionBlock/questions', false, /\.vue$/)
const res_components = {}
allComponents.keys().forEach(fileName => {
  const comp = allComponents(fileName)
  res_components[fileName.replace(/^\.\/(.*)\.\w+$/, '$1')] = comp.default
})

export default {
  name: 'EditTemplate',
  components: {CustomQuestionBlock, CustomRadio, suspendSideBar, ...res_components, tenkvHeader, tenkvTail},
  data() {
    return {
      chooseHeader: null,
      chooseTail: null,
      name: '',
      description: '无',
      hardCode,
      tailForm: {...sptail},
      headerFormOrigin: JSON.parse(JSON.stringify(headerFormOrigin)),
      headerTemplates: [],
      bodyTemplates: [],
      tailTemplates: []
    }
  },
  filters: {
    cleanJson(json) {
      return getClearFormJson(json)
    }
  },
  watch: {
    chooseHeader(newval) {
      if (newval !== null) {
        if (newval.json === null) {
          return
        } else {
          if (newval.json != null) {
            this.$refs.Header.setFormJson(getClearFormJson(newval.json))
          }
        }
      }
    },
    chooseTail(newval) {
      if (newval !== null) {
        if (newval.json === null) {
          return
        } else {
          if (newval.json != null) {
            this.$refs.Tail.setFormJson(getClearFormJson(newval.json))
          }
        }
      }
    }
  },
  computed: {
    editTemplatesStatus() {
      return this.$store.getters.editTemplates
    },
    headOid() {
      return this.chooseHeader.oid
    },
    tailOid() {
      return this.chooseTail.oid
    },
    bodyOid() {
      const chosen = this.$store.getters.editTemplates.chosenTemplates
      const rt = []
      chosen.forEach((item1) => {
        if (item1.oid) {
          rt.push(item1.oid)
          return
        }
        const find = this.bodyTemplates.filter((item) => {
          return item.name === `q${item1.id}`
        })
        rt.push(find[0].oid)
      })
      return rt
    }
  },
  async mounted() {
  },
  async created() {
    try {
      const [bodyResponse, headerResponse, tailResponse] = await Promise.all([
        getTemplateBody(),
        getTemplateHeader(),
        getTemplateTail()
      ]);
      this.bodyTemplates = bodyResponse.data.data;
      this.headerTemplates = headerResponse.data.data;
      this.tailTemplates = tailResponse.data.data;
    } catch (error) {
      console.error('发生错误：', error);
    }
    await this.$store.dispatch('app/setTemplates', [...this.bodyTemplates])
    //加载Info
    const info = this.$route.params.info
    console.log(info)
    if (info) {
      this.name = info.name
      this.description = info.title
      if (info.description) {
        const {header, tail} = JSON.parse(info.description)
        if (header.hasOwnProperty('retData')) {
          this.headerFormOrigin = header.retData
          this.tailForm = tail.retData
        } else {
          if (!Array.isArray(header.config)) {
            if (parseFloat(header.config).toString() === 'NaN') {
              header.configCustom = header.config
              header.config = []
            } else {
              header.config = [header.config]
              header.configCustom = ''
            }
            this.headerFormOrigin = header
            this.tailForm = tail
          }
        }

        this.chooseHeader = this.headerTemplates.find((item) => {
          return item.oid === info.header_id
        })
        this.chooseTail = this.tailTemplates.find((item) => {
          return item.oid === info.tail_id
        })
      }
      info.body_list.forEach((item) => {
        const find = this.editTemplatesStatus.templates.find((item1) => {
          return item1.oid === item
        })
        this.$store.dispatch('app/appendTemplates', find)
      })
    } else {
      if (this.$route.query.mode !== '1') {
        this.$router.push({path: '/staffingSys/orderTemplate'})
      }
    }
  },

  methods: {
    getClearFormJson,
    submit() {
      if (this.name === '' || this.description === '' || this.bodyOid.length === 0) {
        this.$message.error('信息填写不完全，请检查！')
      } else {
        if (this.$route.query.mode === '1') {
          const header = this.$refs.Header.getFormData(false)
          const tail = this.$refs.Tail.getFormData(false)
          console.log(header)
          const data = JSON.stringify({header, tail})
          addTemplate({
            name: this.name,
            title: this.description,
            description: data,
            header_id: this.headOid,
            tail_id: this.tailOid,
            body_list: this.bodyOid
          }).then(res => {
            this.$message.success('添加完成')
            setTimeout(() => {
              this.$router.push({path: '/staffingSys/orderTemplate'})
            }, 500)
          })
        } else {
          const header = this.$refs.Header.getFormData(false)
          const tail = this.$refs.Tail.getFormData(false)
          const data = JSON.stringify({header, tail})
          modifyTemplate(this.$route.params.info.aid, {
            name: this.name,
            title: this.description,
            description: data,
            header_id: this.headOid,
            tail_id: this.tailOid,
            body_list: this.bodyOid
          }).then(res => {
            this.$message.success('修改完成')
            setTimeout(() => {
              this.$router.push({path: '/staffingSys/orderTemplate'})
            }, 500)
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.list-complete-item {
  transition: all 0.8s ease;
  //display: inline-block;
}

.list-complete-enter, .list-complete-leave-to
  /* .list-complete-leave-active for below version 2.1.8 */
{
  opacity: 0;
  transform: translateX(80px);
}

.list-complete-leave-active {
  position: absolute;
}
</style>
